// pages/time-tasks/time-tasks.js
const app = getApp()

Page({
  data: {
    tasks: [],
    loading: true,
    page: 1,
    limit: 10,
    hasMore: true
  },

  onLoad: function (options) {
    this.loadTimeTasks()
  },

  onShow: function () {
    this.loadTimeTasks()
  },

  onPullDownRefresh: function () {
    this.refreshTasks()
  },

  onReachBottom: function () {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMore()
    }
  },

  // 加载计时任务列表
  loadTimeTasks: function () {
    if (this.data.loading) return

    this.setData({ loading: true })

    app.request({
      url: '/getTimeTasks',
      method: 'GET'
    }).then((res) => {
      if (res.code === 1) {
        const newTasks = res.data || []
        
        this.setData({
          tasks: newTasks,
          hasMore: false
        })
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none'
        })
      }
    }).catch((err) => {
      console.error('加载计时任务失败:', err)
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      })
    }).finally(() => {
      this.setData({ loading: false })
      wx.stopPullDownRefresh()
    })
  },

  // 刷新任务列表
  refreshTasks: function () {
    this.setData({
      page: 1,
      hasMore: true
    })
    this.loadTimeTasks()
  },

  // 加载更多
  loadMore: function () {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        page: this.data.page + 1
      })
      this.loadTimeTasks()
    }
  },

  // 点击任务
  onTaskTap: function (e) {
    const task = e.currentTarget.dataset.task
    wx.navigateTo({
      url: `/pages/time-report/time-report?task_id=${task.id}`
    })
  }
})
